# -*- coding:utf-8 -*-
#!/usr/bin/env python3
import uuid
import base64
import os
import sys
from PyQt4.QtCore import *
from PyQt4.QtSql import (QSqlDatabase, QSqlQuery, QSqlTableModel)
from PyQt4.QtGui import *
import time
import datetime,math
from lib.pyhk import *
#打包命令PyInstaller -F -w smq.py
import win32con
import ctypes
import ctypes.wintypes
import threading
RUN=False #用来传递运行一次的参数
mainfram = None
user32 = ctypes.windll.user32  #加载user32.dll
id1=105 #注册热键的唯一id，用来区分热键
import win32api
name = 'aaa'  # 要添加的项值名称
loc = os.getcwd()
print(loc)
os.chdir(loc)
path = loc+'\WDM_go.exe'  # 要添加的exe路径
print(path)
from win32com.shell import shell
from win32com.shell import shellcon
shortcut = pythoncom.CoCreateInstance(
        shell.CLSID_ShellLink, None,
        pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
shortcut.SetPath(path)
shortcut.SetWorkingDirectory(loc)#设置快捷方式的起始位置（即文件所在的目录）
lnkname = path+".lnk"
shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(lnkname,0)
# 注册表项名
KeyName = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run'
# 异常处理
try:
    key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,  KeyName, 0,  win32con.KEY_ALL_ACCESS)
    win32api.RegSetValueEx(key, name, 0, win32con.REG_SZ, lnkname)
    win32api.RegCloseKey(key)
except:
    print('error')
print('添加成功！')


main_frame  = None

one_move = False

MAC = True
try:
    from PyQt4.QtGui import qt_mac_set_native_menubar
except ImportError:
    MAC = False

ID, CATEGORY, SHORTDESC, LONGDESC,FONTSIZE = range(5)


def hkfunc():
    # print 'afe'
    import subprocess
    # subprocess.call(r"D:\do\Python\py_gui\v1\dist\WDMSET-v1.exe")
    subprocess.Popen(r"WDMSET-v1.exe", shell=False, close_fds=True)
# 创建hotkey句柄
hot_handle1 = pyhk()
hot_handle1.addHotkey(['Ctrl', 'T'], hkfunc)



from ctypes import c_bool, c_int, WINFUNCTYPE, windll
from ctypes.wintypes import UINT

prototype = WINFUNCTYPE(c_bool, c_int, c_int, UINT, UINT)
paramflags = (1, 'hWnd', 0), (1,'id', 0), (1,'fsModifiers', 0), (1,'vk', 0)


class FirstWindow(QWidget):

    close_signal = pyqtSignal()
    def __init__(self, parent=None):
        # super这个用法是调用父类的构造函数
        # parent=None表示默认没有父Widget，如果指定父亲Widget，则调用之
        super(FirstWindow, self).__init__(parent)
        self.resize(0,0)
        self.hide()
        # self.leName = QLineEdit(self)
        # self.leName.setPlaceholderText(u'用户名')
        self.lePassword = QLineEdit(self)
        self.lePassword.setEchoMode(QLineEdit.Password)
        self.lePassword.setPlaceholderText(u'密码')
        self.run_day = time.localtime().tm_yday
        self.now_day = time.localtime().tm_yday
        self.m30_7once = True

        self.pbLogin = QPushButton(u'登录', self)
        self.pbLogin.setFocus()
        # self.pbCancel = QPushButton(u'机器码', self)
        self.setWindowIcon(QIcon("ico.ico"))
        self.setWindowTitle("WDMSET")
        self.setWindowFlags( Qt.Tool | Qt.WindowMinimizeButtonHint | Qt.WindowStaysOnTopHint | Qt.X11BypassWindowManagerHint | Qt.FramelessWindowHint)  #
        self.cx = sqlite3.connect("reference.db", check_same_thread=False)
        self.myquery = self.cx.cursor()
        self.removelist = []


        # self.pbLogin.clicked.connect(self.login)
        # self.pbCancel.clicked.connect(self.reject)

        layout = QVBoxLayout()
        # layout.addWidget(self.leName)
        layout.addWidget(self.lePassword)


        # 放一个间隔对象美化布局
        spacerItem = QSpacerItem(20, 48, QSizePolicy.Minimum, QSizePolicy.Expanding)
        layout.addItem(spacerItem)

        # 按钮布局
        buttonLayout = QHBoxLayout()
        # 左侧放一个间隔
        spancerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        buttonLayout.addItem(spancerItem2)
        buttonLayout.addWidget(self.pbLogin)
        # buttonLayout.addWidget(self.pbCancel)

        layout.addLayout(buttonLayout)

        self.setLayout(layout)
        self.setWindowOpacity(0)

        # if not regised():
        #     value, ok = QInputDialog.getText(self, u"提醒", u"未注册，请输入注册码，完成注册", QLineEdit.Normal, u"请输入注册码，您的机器码为:"+get_mac_address())
        #     self.register(value)

        try:
            thread = MyThread()  # 创建一个线程
            thread.sec_changed_signal.connect(self.update)  # 线程发过来的信号挂接到槽：update
            self.pbLogin.clicked.connect(lambda: thread.start())
            thread.start()

        except ZeroDivisionError as err:  # as 加原因参数名称
            print('Exception: ', err)



    def close(self):
        self.hide()
        return False


                # try:
        #     threadHot = MyThreadHot()  # 创建一个线程
        #     threadHot.sec_changed_signal.connect(self.hot)  # 线程发过来的信号挂接到槽：update
        #     self.pbLogin.clicked.connect(lambda: threadHot.start())
        #     threadHot.start()
        #
        # except ZeroDivisionError as err:  # as 加原因参数名称
        #     print('Exception: ', err)



        self.m30_7once = True #每天提醒一次 True为未提醒 False 为已提醒



        # self.RegisterHotKey = prototype(('RegisterHotKey', windll.user32), paramflags)
        #
        # r = self.RegisterHotKey(c_int(self.mainWindow.winId()), HOT_KEY_ID, config.modifier, ord(config.hotkey.upper()))
        # if not r:
        #     QMessageBox.critical(None, 'Hot key', "Can't Register Hotkey Win + Z")
        #     sys.exit(1)



    def hot(self):
        print('11')

    #     # self.show()

    def register(self,value):
        if value == encode(get_mac_address()):
            print(u"注册码正确，写入文件返回成功")
            with open('./register', 'w') as f:
                f.write(value)
                f.close()
        else:
            value, ok = QInputDialog.getText(self, u"提醒", u"注册码不正确，请重新输入注册码，完成注册", QLineEdit.Normal,
                                             u"请输入注册码，您的机器码为:" + get_mac_address())
            self.register(value)

    def update(self):
        # QMessageBox.about(self, '提醒', "密码输入错误，请重试")
        self.now_day = time.localtime().tm_yday
        if self.run_day != self.now_day:
            self.m30_7once = True
        # print(str(sec))
        self.process()

        # self.btn = QToolButton(self)
        # self.btn
        # .setText("click")

    def process(self):
        #threading.Thread(target=self.threadRun).start()
        print("process")
        select_date = self.myquery.execute('SELECT * FROM reference').fetchall()
        # print(select_date)
        res = select_date
        # print res
        try:
            for line in res:
                # print line[0]
                # print(u"提醒前查询"+str(line[0]) + line[1] + line[2])
                self.showWarn(line[1], line[2], line[3], str(line[0]), line[4])
                # except ZeroDivisionError as err:  # as 加原因参数名称
                # print('Exception: ', err)
        finally:
            self.m30_7once = False
            # for rminfo in self.removelist:
            #     self.removeWarn(rminfo["vid"], rminfo["value"])
            str1 = 'QWidget{font-size:12px;}'
            # self.setStyleSheet(str1)
            # time.sleep(10)
            # self.update(1)
            # print(self.m30_7once)
            # self.count = self.count + 1
            # print(self.count)

    def removeWarnbefore(self,vid, value):
        sdict = {}
        sdict['vid']=vid
        sdict['value']=value
        self.removelist.append(sdict)
        print(self.removelist)


    def showWarn(self,vtime,vdesc,vyzm,vid,vfontsize):
        try:
            category = vtime
            print(category)
            waring_t = time.strptime(category, "%Y-%m-%d")
            print(waring_t)
            waring_time = time.mktime(waring_t)
            print(waring_time)
            now = time.localtime(time.time())
            nowtime = time.time()
            print(now)
            print(nowtime)
            str1 = 'QWidget{font-size:' + str(vfontsize) + 'px;}'
            print(str1)

            left = math.floor((waring_time - nowtime)/(24*60*60))
            print("left"+str(left))
            if left<0:
                left = 0

            desc = vdesc
            desc = desc.replace('{left}', '<span style=color:red; size=50px >' + str(int(left)) + '</span>')
            warning = u"提醒时间：" + category + u";提醒内容:" + desc;
            print(u"验证码为："+vyzm)
            if left < 30:
                if left > 7 and self.m30_7once:
                    if vyzm == u'是':
                        # print('进入大于七天')
                        infoBox = InputDialog(desc, vfontsize, 1, vid, left)
                        # self.setStyleSheet(str1)
                        # self.setWindowFlags(Qt.WindowMinimizeButtonHint| Qt.WindowStaysOnTopHint)
                        infoBox.show()
                        # value = infoBox.selectName()
                        # #print(value)
                        # self.removeWarnbefore(vid, value)
                    else:
                        infoBox = InputDialog(desc, vfontsize, 0, vid, left)
                        infoBox.show()
                if left <= 7:
                    global one_move
                    if vyzm == u'是':
                        print('进入小于七天且鼠标未点击')
                        if one_move == False:
                            print('鼠标未点击过')
                            infoBox = InputDialog(desc, vfontsize, 1, vid, left)
                            # self.setStyleSheet(str1)
                            # self.setWindowFlags(Qt.WindowMinimizeButtonHint| Qt.WindowStaysOnTopHint)
                            infoBox.show()
                        else:
                            print('鼠标点击过')
                            print("创建窗口初始化one_move")
                            # global one_move
                            one_move = False
                            print("one_move初始化")
                            print(one_move)
                        # value = infoBox.selectName()
                        # #print(value)
                        # self.removeWarnbefore(vid, value)
                    else:
                        infoBox = InputDialog(desc, vfontsize, 0, vid, left)
                        infoBox.show()
        except Exception as e:
            print(e)
            print('download exception %s' % str1)



    def removeWarn(self,vid,value):

        print(vid+u" 验证码为:"+value)
        try:
            sql = "select count(*) from sjm where sjmm='"+value+"'"
            print(sql)
            self.myquery.exec_(sql)
            print(self.myquery)
            if self.myquery.next():
                num = self.myquery.value(0)
                print(self.myquery.value(0))
                if num == 1:
                    print(u'正确的随机码')
                    vsql = "delete  from reference where id='" + vid + "'"
                    print(vsql)
                    self.myquery.exec_(vsql)

                    vsql = "delete  from sjm where sjmm='" + value + "'"
                    print(vsql)
                    self.myquery.exec_(vsql)

                # return True
            else:
                print(u'错误的随机码')
                # return True
        except ZeroDivisionError as err:  # as 加原因参数名称
            print('Exception: ', err)




    def login(self,fm):
        """返回True或False"""
        input_pw = self.lePassword.text()
        print(input_pw)
        if input_pw == '120607':
            print(fm)
            fm.show()
            self.hide()
        else:
            QMessageBox.about(self, '提醒', "密码输入错误，请重试")
    def reject(self):
        QInputDialog.getText(self, "信息", "本机机器码为：", QLineEdit.Normal, get_mac_address())

    def closeEvent(self, event):
        self.close_signal.emit()
        self.close()

class InputDialog(QWidget):
    def __init__(self,txnr,ztdx,dtype,vid,left):
        super(InputDialog, self).__init__()
        self.setWindowFlags(Qt.Tool | Qt.WindowMinimizeButtonHint| Qt.WindowStaysOnTopHint | Qt.X11BypassWindowManagerHint| Qt.FramelessWindowHint )#
        self.txnr = txnr
        self.ztdx = ztdx
        self.dtype = dtype
        self.vid = vid
        self.left = left
        # self.setAcceptDrops(True)
        self.initUi()
        # 创建hotkey句柄
        hot_handle = pyhk()
        # hot_handle.addHotkey(['Ctrl', 'T'], self.hkfunc)
        hot_handle.addHotkey(['Ctrl', 'B'], self.close)
        self.cx = sqlite3.connect("reference.db")
        self.myquery = self.cx.cursor()
        self.machine = QStateMachine()
        self.installEventFilter(self)
        if self.left!=0 or self.dtype!=1:
            self.createContextMenu()



    def eventFilter(self, QWidget, event):
        if event.type() == QEvent.Enter or event.type() == QEvent.WindowActivate or event.type() == QEvent.ApplicationActivate:
            print("eventFilter")
            global one_move
            one_move = True
            print(one_move)
        return False



    def showContextMenu(self, pos):
        '''''
        右键点击时调用的函数
        '''
        # 菜单显示前，将它移动到鼠标点击的位置
        self.contextMenu.move(self.pos() + pos)
        self.contextMenu.show()

    def createContextMenu(self):
        '''''
        创建右键菜单
        '''
        # 必须将ContextMenuPolicy设置为Qt.CustomContextMenu
        # 否则无法使用customContextMenuRequested信号
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showContextMenu)

        # 创建QMenu
        self.contextMenu = QMenu(self)
        self.actionA = self.contextMenu.addAction(u'关闭')
        #self.actionB = self.contextMenu.addAction(u'动作B')
        #self.actionC = self.contextMenu.addAction(u'动作C')
        # 将动作与处理函数相关联
        # 这里为了简单，将所有action与同一个处理函数相关联，
        # 当然也可以将他们分别与不同函数关联，实现不同的功能
        self.actionA.triggered.connect(self.close)
        #self.actionB.triggered.connect(self.actionHandler)
        #self.actionB.triggered.connect(self.actionHandler)
        screen = QDesktopWidget().screenGeometry()
        # self.resize(screen.width()/2,screen.height()/2)
        size = self.geometry()
        print(u"2尺寸：")
        print(size)
        print(screen)



    # def mousePressEvent(self, event):
    #     # print QEvent.FocusOut, 'mousePressEvent', event.type()
    #     if event.button() == Qt.LeftButton:
    #         self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
    #         QApplication.postEvent(self, QEvent(174))
    #         event.accept()
    #
    # def mouseMoveEvent(self, event):
    #     if event.buttons() == Qt.LeftButton:
    #         self.move(event.globalPos() - self.dragPosition)
    #         event.accept()

    def initUi(self):
        self.setWindowTitle(u"提醒")
        # self.setGeometry(100, 100, 200, 200)


        label1 = QLabel(self.txnr)
        # label1.adjustSize()
        # label1.width = 200
        # label1.setGeometry(QRect(328, 240, 329, 27*4))

        # label1.setAlignment(Qt.AlignTop)

        label1.setAlignment(Qt.AlignCenter)
        label1.setFont(QFont("Roman times", self.ztdx))
        label1.setWordWrap(True)

        self.nameLable = QLineEdit(u"请输入激活码，延期或关闭本弹窗，机器码"+get_mac_address())
        # self.nameLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.styleLable = QLabel("外包")
        self.styleLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.numberLable = QLabel("40")
        self.numberLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.costLable = QLabel("400.98")
        self.costLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.introductionLable = QLabel("服务外包第三方公司")
        self.introductionLable.setFrameStyle(QFrame.Panel | QFrame.Sunken)

        nameButton = QPushButton(u"延期或关闭任务")
        nameButton.clicked.connect(self.selectName)
        styleButton = QPushButton("...")
        styleButton.clicked.connect(self.selectStyle)
        numberButton = QPushButton("...")
        numberButton.clicked.connect(self.selectNumber)
        costButton = QPushButton("...")
        costButton.clicked.connect(self.selectCost)
        introductionButton = QPushButton("...")
        introductionButton.clicked.connect(self.selectIntroduction)

        mainLayout = QGridLayout()
        mainLayout.addWidget(label1, 0, 0)
        if self.dtype == 1:
            mainLayout.addWidget(self.nameLable, 1, 0)
            mainLayout.addWidget(nameButton, 2, 0)


        self.setLayout(mainLayout)

        screen = QDesktopWidget().screenGeometry()
        # self.resize(screen.width()/2,screen.height()/2)
        size = self.geometry()
        print(u"尺寸：")
        print(size)
        print(screen)
        # self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)
        print(u"1尺寸：")
        size1 = self.geometry()
        size2 = self.frameGeometry()
        print(size1)
        print(size2)
        print(screen)
        #
        widthm ,heightm = self.getfunc()
        self.setGeometry(100, 100, widthm, heightm)
        # self.setWindowTitle('OpenCouture Lite')
        self.center()

    def getfunc(self):
        screen = QDesktopWidget().screenGeometry()
        print(u"屏幕尺寸：")
        print(screen)
        mrheight =self.ztdx*1.5
        print(u"屏幕尺寸：")
        # if self.ztdx<=50:
        #     maxhangs = screen.height()/mrheight
        # else:
        #     mrheight = self.ztdx+100
        maxhangs = (screen.height()-100) / mrheight
        maxchangd = screen.width()
        print(u"最大行数：")
        print(maxhangs)
        print(u"显示内容：")
        print(self.txnr)
        zsds = len(self.txnr)
        print(u"字数多少：")
        print(zsds)
        print(u"总计长度：")
        zongjichangdu = zsds*self.ztdx*1.5
        print()
        print(u"行数：")
        linexshu = float(zongjichangdu) / float(screen.width())
        print(linexshu)
        print(u"可容纳行数：")
        minline = int(math.ceil(float(zongjichangdu) / float(screen.width())))
        print(minline)
        print(u"总计行数：")
        kuand = 180
        if linexshu<1:
            danhangkd = int(screen.width()*linexshu)
            print(u'单行宽度')
            print(danhangkd)
            if danhangkd>kuand:
                kuand = danhangkd
        else:
            kuand = screen.width()*0.5

        hangs = int(math.ceil(float(zsds*self.ztdx)/float(kuand)))
        while hangs>maxhangs:
            if kuand<maxchangd-50:
                kuand = kuand+50
                hangs = int(math.ceil(float(zsds * self.ztdx) / float(kuand)))
            else:
                hangs = maxhangs
                break
        print(u'实际宽度为：')
        print(kuand)
        print(u'实际行数为：')
        print(hangs)
        print(u"字体大小：")
        print(self.ztdx)
        return kuand,(hangs*mrheight+100)


    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def selectName(self):
        inputext =  self.nameLable.text()
        print("inputext"+inputext)
        try:
            yqsj = decode(inputext)
            print(yqsj)
            yqlist = yqsj.split('_')
            print(yqlist)
            sql = u"select count(*) from sjm where sjmm='" + str(yqlist[1]) + "'"
            print(sql)

            select_date = self.myquery.execute(sql).fetchone()
            print(select_date)
            print(select_date[0])


            if int(select_date[0])==0 and yqlist[0]==get_mac_address() and int(yqlist[2])>0:
                #正确验证码，提示是延期还是结束
                # value, ok = QInputDialog.getText(self, u"提醒", u"请输入延期天数，输入999则删除本任务", QLineEdit.Normal,
                #                                  u"延期天数")
                self.yanqi(yqlist[2],yqlist[1])

            else:
                print(u'错误或已使用过的随机码')
                QMessageBox.warning(self,u'提示',u'错误或已使用过的随机码,请核实')
                # return True
        # except ZeroDivisionError as err:  # as 加原因参数名称
            #print('Exception: ', err)
        finally:
            self.cx.commit()
    #print('afeiafei')

    def yanqi(self,inputext,sjm):
        try:
            if inputext == '999':
                # print('正确的随机码')
                vsql = "delete  from reference where id='" + str(self.vid) + "'"
                # print(vsql)
                self.myquery.execute(vsql)

                vsql = "insert into sjm(sjmm)  values('" + str(sjm) + "')"
                print(vsql)
                self.myquery.execute(vsql)
                # 关闭本窗口
                self.hide()
            else:
                #延期操作
                print(inputext)
                print(self.left)
                delte_day = int(self.left)+int(inputext)
                print(delte_day)
                now = datetime.datetime.now()
                delta = datetime.timedelta(days=delte_day)
                n_days = now + delta
                delta_data = n_days.strftime('%Y-%m-%d')
                print delta_data
                # # print('正确的随机码')
                vsql = "update reference set category='"+str(delta_data)+"' where id='" + str(self.vid) + "'"
                print(vsql)
                self.myquery.execute(vsql)
                vsql = "insert into sjm(sjmm)  values('" + str(sjm) + "')"
                print(vsql)
                self.myquery.execute(vsql)
                # 关闭本窗口
                self.hide()
        except ZeroDivisionError as err:  # as 加原因参数名称
            print('Exception: ', err)
        finally:
            self.cx.commit()

    def selectStyle(self):
        list = ["外包", "自研"]

        style, ok = QInputDialog.getItem(self, "项目性质", "请选择项目性质：", list)
        if ok:
            self.styleLable.setText(style)

    def selectNumber(self):
        number, ok = QInputDialog.getInt(self, "项目成员", "请输入项目成员人数：", int(self.numberLable.text()), 20, 100, 2)
        if ok:
            self.numberLable.setText(str(number))

    def selectCost(self):
        cost, ok = QInputDialog.getDouble(self, "项目成本", "请输入项目成员人数：", float(self.costLable.text()), 100.00, 500.00, 2)
        if ok:
            self.costLable.setText(str(cost))

    def selectIntroduction(self):
        introduction, ok = QInputDialog.getMultiLineText(self, "项目介绍", "介绍：", "服务外包第三方公司 \nPython project")
        if ok:
            self.introductionLable.setText(introduction)


def get_mac_address():
    mac=uuid.UUID(int = uuid.getnode()).hex[-12:]
    mac = ":".join([mac[e:e+2] for e in range(0,11,2)])
    macstr = mac.replace(':', '')
    return macstr

def encode(str):
    bytesString = str.encode(encoding="utf-8")
    #print(bytesString)
    # base64 编码
    encodestr = base64.b64encode(bytesString)
    #print(encodestr)
    print(encodestr.decode())
    return encodestr.decode()

def decode(encode_str):
    decodestr = base64.b64decode(encode_str)
    #print(decodestr.decode())
    return decodestr.decode()

import sqlite3
def getencode():
    try:
        conn = sqlite3.connect('reference.db')
        cursor = conn.cursor()
        sql = '''select sjmm from sjm limit 1'''
        results = cursor.execute(sql)
        one_sjm = results.fetchone()[0]
        sql = "delete from sjm where sjmm = '"+one_sjm+"'"
        print(sql)
        cursor.execute(sql)
        conn.commit()
        return one_sjm
    except ZeroDivisionError as err:  # as 加原因参数名称
            print('Exception: ', err)

# mac = get_mac_address()
# encode_str = encode(mac)
# print(decode(encode_str))

class MyThread(QThread):
    sec_changed_signal = pyqtSignal(int)  # 信号类型：int

    def __init__(self, sec=1000, parent=None):
        QThread.__init__(self, parent)
        # super().__init__(parent)
        self.sec = sec  # 默认1000秒


    def run(self):
        for i in range(self.sec):
            # time.sleep(1)
            self.sec_changed_signal.emit(i)  # 发射信号
            time.sleep(60 * 60) #





mac = get_mac_address()
def regised():
    is_registered = False
    if os.path.exists('register'):
        print('文件存在')
        try:
            f = open('./register', 'r')
            if f:
                key = f.read()
                if key:
                    encode_str = encode(mac)
                    if encode_str != key:
                        print('注册码不正确,未注册')
                    else:
                        print('已注册')
                        is_registered = True
        except IOError:
            print(IOError)
    else:
        print('文件不存在')

    return is_registered


def main():
    global RUN,mainfram
    app = QApplication(sys.argv)
    filename = os.path.join(os.path.dirname(__file__), "reference.db")
    create = not QFile.exists(filename)

    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(filename)
    if not db.open():
        QMessageBox.warning(None, "Reference Data",
            "Database Error: {0}".format(db.lastError().text()))
        sys.exit(1)



    if create:
        query = QSqlQuery()


    # main_frame = ReferenceDataDlg()
    ex = FirstWindow()
    # ex.pbLogin.clicked.connect(lambda: ex.login(main_frame))
    # # ex.pbLogin.clicked.connect(ex.hide)
    # ex.close_signal.connect(ex.close)
    ex.show()
    # myquery = QSqlQuery()

    # thread1 = myThread(1, "Thread-1", 60, myquery,form)
    # thread1.start()

    sys.exit(app.exec_())

main()